<?php
declare (strict_types = 1);

namespace app\controller\backend;

use app\model\Category;
use app\model\Model;
use app\model\Nav;
use app\model\NavCate;
use app\model\Route;
use app\validate\NavValidate;
use think\exception\ValidateException;


class NavController extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     */
    public function index(Nav $nav): \think\response\Json
    {
        $param = input('param.');
        try{
            validate(NavValidate::class)->scene('index')->check($param);
        }catch (ValidateException $e){
            return jsonReturn(-1,$e->getError());
        }
        $where = [
            'seller_id' => $this->admin['seller_id'],
            'nav_cate_id' => $param['cate_id'],
            'website_id' => $param['website_id'],
            'lang' => $param['lang'],
        ];
        $navList = $nav->getNavList($where)['data']->toArray();
        $navList = makeTree($navList);
        return jsonReturn(0,'success',$navList);
    }

    /**
     * 保存新建的资源
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     * @throws \app\exception\ModelNotUniqueException
     */
    public function save(Nav $nav,NavCate $NavCate): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            // 数据验证
            try{
                validate(NavValidate::class)->scene('save')->check($param);
            }catch(ValidateException $e) {
                return jsonReturn(-1, $e->getError());
            }
            $param['seller_id'] = $this->admin['seller_id'];
            if(empty($param['sort'])){
                // 设置排序
                $maxOrder = $nav->getMaxOrderNav(['parent_id' => $param['parent_id'],'seller_id' => $this->admin['seller_id']], 'sort')['data'];
                if (!empty($maxOrder)) {
                    $param['sort'] = (int)$maxOrder + 10;
                }
            }
            // 设置网站ID
            $navCate = $NavCate -> getNavCate(['id'=>$param['nav_cate_id'],'seller_id'=>$this->admin['seller_id']])['data'];
            $param['website_id'] = $navCate['website_id'];
            // 唯一性验证
            $nav->saveUnique(['title'=>$param['title'],'lang'=>$param['lang'],'nav_cate_id'=>$param['nav_cate_id'],'website_id'=>$param['website_id'],'seller_id'=>$param['seller_id'],'parent_id'=>$param['parent_id']],'导航已存在');
            // 设置URL
            if($param['type'] == 2){
                $this->setNavUrl($param);
            }
            $res = $nav -> addNav($param);
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * 显示指定的资源
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function read(Nav $nav): \think\response\Json
    {

        $param = input('param.');
        try {
            validate(NavValidate::class)->scene('read')->check($param);
        }catch (ValidateException $e){
            return  jsonReturn(-1,$e->getError());
        }

        $where = [
            'id' => $param['id'],
            'seller_id' => $this->admin['seller_id'],
            'website_id' => $param['website_id'],
        ];
        $res = $nav->getNav($where);
        return json($res);

    }

    /**
     * 保存更新的资源
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     * @throws \app\exception\ModelNotUniqueException
     */
    public function update(Nav $nav, NavCate $NavCate): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            try {
                validate(NavValidate::class)->scene('update')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-1, $e->getError());
            }
            // 设置网站ID
            $navCate = $NavCate -> getNavCate(['id'=>$param['nav_cate_id'],'seller_id'=>$this->admin['seller_id']])['data'];
            $param['website_id'] = $navCate['website_id'];
            // 唯一性验证
            $nav->updateUnique(['title'=>$param['title'],'website_id'=>$param['website_id'],'nav_cate_id'=>$param['nav_cate_id'],'seller_id'=>$this->admin['seller_id']],$param['id'],'导航已存在');
            // 设置url
            if($param['type'] == 2){
                $this->setNavUrl($param);
            }
            if(empty($param['sort'])){
                // 设置排序
                $maxOrder = $nav->getMaxOrderNav(['parent_id' => $param['parent_id'],'seller_id' => $this->admin['seller_id']], 'sort')['data'];
                if (!empty($maxOrder)) {
                    $param['sort'] = (int)$maxOrder + 10;
                }
            }


            $where = [
                'id' => $param['id'],
                'seller_id' => $this->admin['seller_id'],
            ];
            $res = $nav -> updateNav($where,$param);
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * 删除指定资源
     *
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function delete(Nav $nav): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            try {
                validate(NavValidate::class)->scene('delete')->check($param);
            }catch(ValidateException $e){
                return jsonReturn(-1,$e->getError());
            }
            $where = [
                'id' => $param['id'],
                'seller_id' => $this->admin['seller_id'],
                'website_id' => $param['website_id'],
            ];
            $children = $nav->getNavList([
                    'parent_id' => $param['id'],
                    'seller_id' => $this->admin['seller_id'],
                    'website_id' => $param['website_id'],
            ])['data']->toArray();
            if(count($children)){
                $res = ['code'=>-4,'msg'=>'有子菜单不能删除'];
            }else{
                $res = $nav->delNav($where);
            }
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * @throws \app\exception\ModelEmptyException
     * @throws \app\exception\ModelException
     */
    public function setNavUrl(&$param)
    {
        $Category = new Category();
        $category = $Category -> getCategory(['id'=>$param['category_id'],'seller_id' => $this->admin['seller_id']])['data'];
        if($category['type'] == 2){
            $param['href'] = 'javascript:;';
        }else if($category['type'] == 3){
            $param['href'] = $category['alias'];
        } else{
            $Route = new Route();
            $route = $Route -> getRoute(['full_url'=> 'List/index?id='.$param['category_id'],'seller_id'=>$this->admin['seller_id']])['data'];
            $param['href'] = $route['url'];
        }
    }
}
